package com.dyoung.carpool.node.greendao.core;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.SqlUtils;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import com.dyoung.carpool.node.greendao.model.NodeType;
import com.dyoung.carpool.node.greendao.model.NoteTypeConverter;
import com.dyoung.carpool.node.greendao.model.Trip;

import com.dyoung.carpool.node.greendao.model.CarPoolNode;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table "CAR_POOL_NODE".
*/
public class CarPoolNodeDao extends AbstractDao<CarPoolNode, Long> {

    public static final String TABLENAME = "CAR_POOL_NODE";

    /**
     * Properties of entity CarPoolNode.<br/>
     * Can be used for QueryBuilder and for referencing column names.
     */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property TripId = new Property(1, Long.class, "tripId", false, "TRIP_ID");
        public final static Property Status = new Property(2, Integer.class, "status", false, "STATUS");
        public final static Property Num = new Property(3, Integer.class, "num", false, "NUM");
        public final static Property NodeType = new Property(4, String.class, "nodeType", false, "NODE_TYPE");
        public final static Property Number = new Property(5, String.class, "number", false, "NUMBER");
        public final static Property Mark = new Property(6, String.class, "mark", false, "MARK");
        public final static Property Date = new Property(7, Long.class, "date", false, "DATE");
        public final static Property RideTime = new Property(8, Long.class, "rideTime", false, "RIDE_TIME");
    }

    private DaoSession daoSession;

    private final NoteTypeConverter nodeTypeConverter = new NoteTypeConverter();
    private Query<CarPoolNode> trip_CarPoolNodesQuery;

    public CarPoolNodeDao(DaoConfig config) {
        super(config);
    }
    
    public CarPoolNodeDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(Database db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "\"CAR_POOL_NODE\" (" + //
                "\"_id\" INTEGER PRIMARY KEY ," + // 0: id
                "\"TRIP_ID\" INTEGER," + // 1: tripId
                "\"STATUS\" INTEGER," + // 2: status
                "\"NUM\" INTEGER," + // 3: num
                "\"NODE_TYPE\" TEXT," + // 4: nodeType
                "\"NUMBER\" TEXT NOT NULL ," + // 5: number
                "\"MARK\" TEXT," + // 6: mark
                "\"DATE\" INTEGER," + // 7: date
                "\"RIDE_TIME\" INTEGER);"); // 8: rideTime
    }

    /** Drops the underlying database table. */
    public static void dropTable(Database db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"CAR_POOL_NODE\"";
        db.execSQL(sql);
    }

    @Override
    protected final void bindValues(DatabaseStatement stmt, CarPoolNode entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        Long tripId = entity.getTripId();
        if (tripId != null) {
            stmt.bindLong(2, tripId);
        }
 
        Integer status = entity.getStatus();
        if (status != null) {
            stmt.bindLong(3, status);
        }
 
        Integer num = entity.getNum();
        if (num != null) {
            stmt.bindLong(4, num);
        }
 
        NodeType nodeType = entity.getNodeType();
        if (nodeType != null) {
            stmt.bindString(5, nodeTypeConverter.convertToDatabaseValue(nodeType));
        }
        stmt.bindString(6, entity.getNumber());
 
        String mark = entity.getMark();
        if (mark != null) {
            stmt.bindString(7, mark);
        }
 
        Long date = entity.getDate();
        if (date != null) {
            stmt.bindLong(8, date);
        }
 
        Long rideTime = entity.getRideTime();
        if (rideTime != null) {
            stmt.bindLong(9, rideTime);
        }
    }

    @Override
    protected final void bindValues(SQLiteStatement stmt, CarPoolNode entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
 
        Long tripId = entity.getTripId();
        if (tripId != null) {
            stmt.bindLong(2, tripId);
        }
 
        Integer status = entity.getStatus();
        if (status != null) {
            stmt.bindLong(3, status);
        }
 
        Integer num = entity.getNum();
        if (num != null) {
            stmt.bindLong(4, num);
        }
 
        NodeType nodeType = entity.getNodeType();
        if (nodeType != null) {
            stmt.bindString(5, nodeTypeConverter.convertToDatabaseValue(nodeType));
        }
        stmt.bindString(6, entity.getNumber());
 
        String mark = entity.getMark();
        if (mark != null) {
            stmt.bindString(7, mark);
        }
 
        Long date = entity.getDate();
        if (date != null) {
            stmt.bindLong(8, date);
        }
 
        Long rideTime = entity.getRideTime();
        if (rideTime != null) {
            stmt.bindLong(9, rideTime);
        }
    }

    @Override
    protected final void attachEntity(CarPoolNode entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    @Override
    public CarPoolNode readEntity(Cursor cursor, int offset) {
        CarPoolNode entity = new CarPoolNode( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1), // tripId
            cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2), // status
            cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3), // num
            cursor.isNull(offset + 4) ? null : nodeTypeConverter.convertToEntityProperty(cursor.getString(offset + 4)), // nodeType
            cursor.getString(offset + 5), // number
            cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // mark
            cursor.isNull(offset + 7) ? null : cursor.getLong(offset + 7), // date
            cursor.isNull(offset + 8) ? null : cursor.getLong(offset + 8) // rideTime
        );
        return entity;
    }
     
    @Override
    public void readEntity(Cursor cursor, CarPoolNode entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setTripId(cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1));
        entity.setStatus(cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2));
        entity.setNum(cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3));
        entity.setNodeType(cursor.isNull(offset + 4) ? null : nodeTypeConverter.convertToEntityProperty(cursor.getString(offset + 4)));
        entity.setNumber(cursor.getString(offset + 5));
        entity.setMark(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
        entity.setDate(cursor.isNull(offset + 7) ? null : cursor.getLong(offset + 7));
        entity.setRideTime(cursor.isNull(offset + 8) ? null : cursor.getLong(offset + 8));
     }
    
    @Override
    protected final Long updateKeyAfterInsert(CarPoolNode entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    @Override
    public Long getKey(CarPoolNode entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    @Override
    public boolean hasKey(CarPoolNode entity) {
        return entity.getId() != null;
    }

    @Override
    protected final boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "carPoolNodes" to-many relationship of Trip. */
    public List<CarPoolNode> _queryTrip_CarPoolNodes(Long tripId) {
        synchronized (this) {
            if (trip_CarPoolNodesQuery == null) {
                QueryBuilder<CarPoolNode> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.TripId.eq(null));
                queryBuilder.orderRaw("T.'DATE' ASC");
                trip_CarPoolNodesQuery = queryBuilder.build();
            }
        }
        Query<CarPoolNode> query = trip_CarPoolNodesQuery.forCurrentThread();
        query.setParameter(0, tripId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getTripDao().getAllColumns());
            builder.append(" FROM CAR_POOL_NODE T");
            builder.append(" LEFT JOIN TRIP T0 ON T.\"TRIP_ID\"=T0.\"_id\"");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected CarPoolNode loadCurrentDeep(Cursor cursor, boolean lock) {
        CarPoolNode entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Trip trip = loadCurrentOther(daoSession.getTripDao(), cursor, offset);
        entity.setTrip(trip);

        return entity;    
    }

    public CarPoolNode loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<CarPoolNode> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<CarPoolNode> list = new ArrayList<CarPoolNode>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<CarPoolNode> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<CarPoolNode> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
